import Vue from "vue";
import VueRouter from "vue-router";
import Login from "@/views/login";
import Home from "@/views/Home";
import store from "@/store";
import ajax from "@/utils/ajax";
import { formatMenu } from "@/utils/initMenus";

Vue.use(VueRouter);

const routes = [
  {
    path: "/login",
    component: Login,
  },
  {
    path: "/",
    component: Home,
  },
  {
    path: "/order",
    component: Home,
    redirect: "/order/orderList",
    children: [
      {
        path: "orderList",
        component: () => import("@/views/order/order"),
      },
      {
        path: "stemealList",
        component: () => import("@/views/order/stemeal"),
      },
      {
        path: "orderSuccess",
        component: () => import("@/views/order/orderSuccess"),
      },
    ],
  },
];

const router = new VueRouter({
  mode: "history",
  routes,
});

/**
 * 路由导航
 * to : 将要去哪个页面
 * from : 从哪个页面过来
 * next : 放行到哪个页面
 */
router.beforeEach((to, from, next) => {
  console.log(router);
  // 判断用户是否登录  （可以从缓存中获取token信息）
  const token = sessionStorage.getItem("token");
  if (!token) {
    if (to.path === "/login") {
      next();
    } else {
      next(`/login?redirect=${to.fullPath}`); // 未登录访问其他页面时 重定向至登录页
    }
  } else {
    // 向后端发送请求，获取用户基本信息
    ajax.get("/user/getInfo").then((res) => {
      console.log("用户信息", res);
      // 在本地缓存，vuex中存入用户信息
      const user = res.data.data; // 获取用户信息
      store.commit("setName", user.name);
      store.commit("setAvatar", user.avatar);
      store.commit("setNickName", user.nickName);
      // 用户角色权限多对多
      if (user.roles.length > 0) {
        // 添加角色、带单、权限等信息 ，存入本地
        store.commit("setRoles", user.roles);
        // 格式化菜单
        const menuList = formatMenu(user.menus);
        router.addRoutes(menuList);
        store.commit("setMenus", menuList);
        store.commit("setPermissions", user.permissions);
      }
    });
    // 已登录
    if (to.path === "/login") {
      next("/home");
    } else {
      next();
    }
  }
});

export default router;
